package com.data.monitoring.service.impl;

import com.data.monitoring.model.entity.MonitoredFolders;
import com.data.monitoring.service.MonitoredFoldersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author 86183
 */
@Service
public class FolderMonitorScheduler {

    @Autowired
    private FolderMonitorService monitorService;

    @Autowired
    private MonitoredFoldersService folderRepository;

    // 使用ScheduledExecutorService管理所有监控任务
    private final Map<Long, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();
    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);

    /**
     * 启动所有活跃的监控任务
     */
    @PostConstruct
    public void startAllMonitors() {
        List<MonitoredFolders> folders = folderRepository.findByIsActiveTrue();
        folders.forEach(this::scheduleMonitor);
    }

    /**
     * 安排单个文件夹的监控任务
     */
    public void scheduleMonitor(MonitoredFolders folder) {
        // 取消现有的任务（如果存在）
        cancelMonitor(Long.valueOf(folder.getFolderId()));

        // 创建新的定时任务
        ScheduledFuture<?> future = executor.scheduleAtFixedRate(
                () -> monitorService.checkFolder(folder),
                0,
                folder.getCheckInterval(),
                TimeUnit.SECONDS
        );

        scheduledTasks.put(Long.valueOf(folder.getFolderId()), future);
    }

    /**
     * 取消监控任务
     */
    public void cancelMonitor(Long folderId) {
        ScheduledFuture<?> future = scheduledTasks.get(folderId);
        if (future != null) {
            future.cancel(false);
            scheduledTasks.remove(folderId);
        }
    }

    /**
     * 更新监控间隔
     */
    @Transactional
    public void updateCheckInterval(Long folderId, Integer newInterval) {
        MonitoredFolders folder = folderRepository.getById(folderId);

        folder.setCheckInterval(newInterval);
        folderRepository.save(folder);

        // 重新安排任务
        scheduleMonitor(folder);
    }
}